<template>
  <div class="editpersonal">
    <myheader title="编辑个人信息">
      <!-- slot:通过slot可以指定将这个结构填充到子组件的哪个插槽中 -->
      <span slot="left" class="iconfont iconjiantou2" @click="$router.back()"></span>
      <!-- <span slot='right'>搜索</span> -->
    </myheader>
    <!-- 图片及上传 -->
    <div class="userimg">
      <img :src="current.head_img" alt />
      <van-uploader :after-read="afterRead" />
    </div>
    <mycell title="昵称" :desc="current.nickname" @click="nickshow = !nickshow"></mycell>
    <van-dialog v-model="nickshow" title="修改昵称" show-cancel-button @confirm="updatenickname">
      <van-field
        :value="current.nickname"
        label="文本"
        placeholder="请输入用户名"
        ref="nick"
        required
        @input="handlernickname"
      />
    </van-dialog>

    <mycell title="密码" :desc="current.password" type="pass" @click="passshow=!passshow"></mycell>
    <van-dialog
      v-model="passshow"
      title="修改密码"
      show-cancel-button
      @confirm="updatepassword"
      :before-close="beforeClose"
    >
      <van-field
        placeholder="请输入原始密码"
        required
        label="原密码"
        @input="handlerOringinPass"
        :value="originpass"
      />
      <van-field
        placeholder="请输入新密码"
        required
        label="新密码"
        @input="handlerNewPass"
        :value="newpass"
      />
    </van-dialog>
    <mycell title="性别" :desc="current.gender==1?'男':'女'" @click="gendershow=!gendershow"></mycell>
    <van-dialog v-model="gendershow" title="修改性别" show-cancel-button @confirm="updategender">
      <van-picker
        title="修改性别"
        :columns="['女','男']"
        :defaultIndex="current.gender"
        @change="getgender"
      />
    </van-dialog>
  </div>
</template>

<script>
import myheader from "@/components/myheader.vue";
import mycell from "@/components/mycell.vue";
import { getUserDetail, editPersonalInfo } from "@/apis/users.js";
import { uploadFile } from "@/apis/fileUpload.js";
import myaxios from "@/utils/myaxios.js";

export default {
  data() {
    return {
      current: {},
      nickshow: false,
      passshow: false,
      gendershow: false,
      username: "", // 这就是用户的输入的昵称
      originpass: "",
      newpass: "",
      usergender: "",
    };
  },
  components: {
    myheader,
    mycell,
  },
  async mounted() {
    let id = this.$route.params.id;
    // 根据参数获取用户详情数据，实现动态渲染
    let res = await getUserDetail(id);
    console.log(res);
    if (res.data.message == "获取成功") {
      this.current = res.data.data;
      // 对图片进行处理
      // 1.如果 有图片数据，应该在路径前面拼接 基准路径
      // 2.如果没有图片数据，也应该赋值一个默认图片路径
      if (res.data.data.head_img) {
        this.current.head_img =
          myaxios.defaults.baseURL + this.current.head_img;
      } else {
        this.current.head_img =
          myaxios.defaults.baseURL + "/uploads/images/default.png";
      }
    }
  },
  methods: {
    // 获取用户所选择的性别的索引值，而这个值刚好和我们的数据对应
    getgender(a, b, index) {
      console.log(a, b, index);
      this.usergender = index;
    },
    // 收集用户所输入的昵称
    handlernickname(data) {
      this.username = data;
    },
    handlerOringinPass(data) {
      this.originpass = data;
    },
    handlerNewPass(data) {
      this.newpass = data;
    },
    // 修改头像
    async afterRead(file) {
      let formdata = new FormData();
      formdata.append("file", file.file);
      // 此时可以自行将文件上传至服务器
      let res = await uploadFile(formdata);
      // console.log(res)
      if (res.data.message == "文件上传成功") {
        this.current.head_img = myaxios.defaults.baseURL + res.data.data.url;
        // 上传文件成功文件，立刻进行用户图像的更新,注意所需要的参数数据是后台返回的图片的目录数据，而不是包含了服务器地址的
        let result = await editPersonalInfo(this.current.id, {
          head_img: res.data.data.url,
        });
        console.log(result);
        if (result.data.message == "修改成功") {
          this.$toast.success("修改用户头像成功");
        } else {
          this.$toast.fail("修改用户头像失败");
        }
      } else {
        this.$toast.fail("文件上传失败，请重试");
      }
    },
    // 修改昵称
    async updatenickname() {
      console.log(this.username);
      if (this.username.trim().length == 0) {
        this.$toast.warning("请输入用户名");
      } else {
        let result = await editPersonalInfo(this.current.id, {
          nickname: this.username,
        });
        console.log(result);
        if (result.data.message == "修改成功") {
          this.current.nickname = this.username;
          this.$toast.success("修改用户昵称成功");
        } else {
          this.$toast.fail("修改用户昵称失败");
        }
      }
    },
    // 修改密码
    async updatepassword() {
      console.log(this.current.password);
      // 1.先判断用户输入的原密码是否与真实密码匹配
      if (this.originpass == this.current.password) {
        let result = await editPersonalInfo(this.current.id, {
          password: this.newpass,
        });
        console.log(result);
        if (result.data.message == "修改成功") {
          // 这一步一定要做，否则用户不刷新的情况下，组件不会重新加载， 意味着mounted钩子不会再执行，从而导致current中的数据没有更新
          this.current.password = this.newpass;
          this.$toast.success("修改用户密码成功");
          // 清空
          this.originpass = this.newpass = "";
        } else {
          this.$toast.fail("修改用户密码失败");
        }
      } else {
        this.$toast.fail("原始密码输入错误");
      }
    },
    beforeClose(action, done) {
      console.log(action);
      if (action == "confirm") {
        // done(false)
        // 什么时候需要阻止模态框的关闭：在用户单击确认情况下，当用户的原始密码输入错误的时候，才需要阻止
        if (this.originpass != this.current.password) {
          done(false);
        } else {
          done();
        }
      } else {
        this.originpass = this.newpass = "";
        done();
      }
    },
    async updategender() {
      let result = await editPersonalInfo(this.current.id, {
        gender: this.usergender,
      });
      if (result.data.message == "修改成功") {
        this.current.gender = this.usergender;
        this.$toast.success("修改用户性别成功");
      } else {
        this.$toast.fail("修改用户性别失败");
      }
    },
  },
};
</script>

<style lang="less" scoped>
.editpersonal {
  .userimg {
    width: 100%;
    height: 150px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    img {
      width: 90/360 * 100vw;
      height: 90/360 * 100vw;
      border-radius: 50%;
    }
    /deep/.van-uploader__upload {
      width: 90/360 * 100vw;
      height: 90/360 * 100vw;
    }
    /deep/.van-uploader {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      opacity: 0;
    }
  }
}
</style>